<?php

use console\db\Migration;
use yii\db\Query;

/**
 * 更新动态格式:单图
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300020_000015_t_sns_dynamic_format_image extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%sns_dynamic_gallery}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from($this->tableName)
        ->select(['dynamic_id', 'count(*) images'])
        ->where(['comment_id' => 0])
        ->groupBy('dynamic_id');
        $this->handleProgress($query, [$this, 'evenDule']);
    }

    public function safeDown() {
        $this->update('{{%sns_dynamic}}', ['format' => 0], ['!=', 'format', 1]);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        if (empty($rows)) {
            return;
        }
        $one = [];
        $many = [];
        foreach ($rows as $row) {
            if ($row['images'] == 1) {
                $one[] = $row['dynamic_id'];
            } elseif ($row['images'] > 1) {
                $many[] = $row['dynamic_id'];
            }
        }
        if (!empty($one)) {
            $migration->db->createCommand()->update('{{%sns_dynamic}}', [
                'format' => 2
            ], [
                'id' => $one,
                'format' => 0
            ])->execute();
        }
        if (!empty($many)) {
            $migration->db->createCommand()->update('{{%sns_dynamic}}', [
                'format' => 3
            ], [
                'id' => $many,
                'format' => 0
            ])->execute();
        }
    }

}
